// pages/my/info/info.js
let app = getApp()
let util = require('../../../utils/index');
import Toast from "../../components/toast/toast.js";
import http from '../../../services/http/index'
import userStore from '../../../store/user'
import { USER_INFO } from '../../../constants/user'
import { PlainData } from '../../../utils/Data';
import config from '../../../config/index'
const { api: { url: apiBaseUrl } } = config

Page({

  /**
   * 页面的初始数据
   */
  data: {
    hide: true,
    cityIndex: 0,
    userInfo: {}
  },
  // 弹出层的显示与隐藏
  maskToggle() {
    app.maskToggle(this)
  },
  stopBubble() {
    console.log(22)
  },
  bindCityChange(e) {
    this.setData({
      'cityIndex': e.detail.value
    })
  },
  chooseSex(e) {
    let sex = e.currentTarget.dataset.sex;
    var userInfo = this.data.userInfo;
    userInfo.data.info.sex = sex;
    userInfo.data.info.sex_text = sex == 1 ? '男' : '女';
    this.setData({
      userInfo: userInfo
    });
  },
  //修改昵称
  inputBlurName(e) {
    var value = e.detail.value;
    var userInfo = this.data.userInfo;
    userInfo.data.info.nickname = value;
    this.setData({
      userInfo: userInfo
    });
  },
  //上传图片
  uploadImg(e) {
    var _this = this;
    var userInfo = this.data.userInfo;
    var type = e.currentTarget.dataset.type;
    wx.chooseImage({
      count: 1, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: [type], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        console.log(res);
        wx.showToast({
          title: 'loading',
          icon: 'loading',
          duration: 10000,
          mask:true
        });
        var tempFilePaths = res.tempFilePaths[0];
        wx.uploadFile({
          url: apiBaseUrl + '/system/upload',      //此处换上你的接口地址
          filePath: tempFilePaths,
          name: 'file',
          header: {
            "Content-Type": "multipart/form-data",
            'accept': 'application/json'
          },
          formData: {},
          success: function (res) {
            wx.hideToast();
            var data = JSON.parse(res.data);
            console.log(data);
            if (res.statusCode == 200) {
              userInfo.data.info.headimgurl = data.data.link;
              userInfo.data.info.img_id = data.data.id;
              _this.setData({
                userInfo: userInfo
              });
              _this.maskToggle();
            } else {
              Toast.show(_this, 'info', '上传服务器失败');
            }

          },
          fail: function (res) {
            wx.hideToast();
            console.log('fail');
          },
        })

      },
      fail: function () {
        Toast.show(_this, 'info', '选择图片失败');
      }
    });
  },
  saveInfo() {
    wx.showToast({
      title: 'loading',
      icon: 'loading',
      duration: 10000,
      mask:true
    });
    var _this = this;
    let userInfo = this.data.userInfo;
    let cityIndex = this.data.cityIndex;
    let para = {
      img_id: userInfo.data.info.img_id,
      sex: userInfo.data.info.sex,
      nickname: userInfo.data.info.nickname,
      city_id: userInfo.data.cityList[cityIndex].id
    };
    http.saveMyInfo(para)
      .then(data => {
        wx.hideToast();
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
        util.default.go('../index/index',3);
      }).catch(err => {
        wx.hideToast();
        Toast.show(_this, 'info', '保存失败');
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUserInfo();
  },

  //获取个人信息
  getUserInfo() {
    http.getMyInfo()
      .then(data => {
        var city_id = data.info.city_id, city_index = 0
        data.cityList.forEach(function (el, i) {
          if (el.id == city_id) {
            city_index = i
          }
        })
        this.setData({
          userInfo: Object.assign(
            new PlainData(),
            {
              data: data
            }
          ),
          cityIndex: city_index
        });
        console.log(this.data.userInfo);
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.setNavigationBarTitle({
      title: '我的主页'
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})